<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="xu wen liu">
  <meta name="keywords" content="">
  <title>TS中的接口 - NeverGiveUpT</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/5.12.1/css/all.min.css" />
<link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />
<link  rel="stylesheet" href="https://cdn.staticfile.org/mdbootstrap/4.13.0/css/mdb.min.css" />
<link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/3.0.1/github-markdown.min.css" />

<link rel="stylesheet" href="//at.alicdn.com/t/font_1067060_qzomjdt8bmp.css">



  <link  rel="stylesheet" href="/lib/prettify/tomorrow-night-eighties.min.css" />

<link  rel="stylesheet" href="/css/main.css" />


  <link defer rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />


<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="/css/custom.css">



<meta name="generator" content="Hexo 4.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>NeverGiveUpT</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/">首页</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/archives/">归档</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/categories/">分类</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/tags/">标签</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/about/">关于</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/links/">友链</a>
          </li>
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/post.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask rgba-black-light flex-center">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
                <p class="mt-3 post-meta">
                  <i class="fas fa-calendar-alt" aria-hidden="true"></i>
                  2020-05-02 22:47:00
                </p>
              

              <p class="mt-1">
                
                  
                  <span class="post-meta">
                    <i class="far fa-chart-bar"></i>
                    785 字
                  </span>
                

                
                  
                  <span class="post-meta">
                      <i class="far fa-clock"></i>
                      3 分钟
                  </span>
                

                
              </p>
            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5 z-depth-3" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p
                class="note note-warning">本文最后更新于：2020-05-03 17:17:47</p>
            
            <div class="markdown-body">
              <p>接口的作用：定义标准<br>在面向对象的编程中，接口是一种规范的定义，它定义了行为和动作的规范，在程序设计里面，接口起到了一种限制和规范的作用。接口定义了某一批类所需要遵循的规范，接口不关心这些类的内部状态数据，也不关心这些类里方法的实现细节，它只规定这批类里必须提供某些方法，提供这些方法的类就可以满足实际需要。</p>
<h3 id="1-属性接口"><a href="#1-属性接口" class="headerlink" title="1.属性接口"></a>1.属性接口</h3><blockquote>
<p>对json的约束</p>
</blockquote>
<pre><code class="ts">interface IObj {
    name: string;
    age?: number;
}
function getList(obj: IObj): void {
    console.log(obj.name);
    console.log(obj.age);
}
let obj = {
    name: &#39;tom&#39;,
    age: 22,//可选属性，可传，可不传
}
getList(obj);</code></pre>
<pre><code class="ts">interface IObj {
    name: string;
    age: number;
}

function getList(obj: IObj): void {
    console.log(obj.name);
    console.log(obj.age);
}
//定义在外面 只要包含name，age就可以
let obj = {
    name: &#39;tom&#39;,
    age: 20,
    firstName: &#39;t&#39;, //额外的属性
}
getList(obj);

//定义在里面 只能有name，age
getList({
    name: &#39;tom&#39;,
    age: 20,
    firstName: &#39;t&#39;, //错误
});

//正确
getList({
    name: &#39;tom&#39;,
    age: 20,
});
</code></pre>
<h3 id="2-函数接口"><a href="#2-函数接口" class="headerlink" title="2.函数接口"></a>2.函数接口</h3><blockquote>
<p>对函数传入的参数和返回值进行约束</p>
</blockquote>
<pre><code class="ts">interface encrypt {
    (key: string, value: string): string;
}

let md5: encrypt = function (key: string, value: string): string {
    return key + &#39;--md5-&#39; + value;
};

let sha1: encrypt = function (key: string, value: string): string {
    return key + &#39;--sha1-&#39; + value;
};
console.log(md5(&#39;name&#39;, &#39;数学&#39;));
console.log(sha1(&#39;name&#39;, &#39;历史&#39;));</code></pre>
<h3 id="3-可索引接口"><a href="#3-可索引接口" class="headerlink" title="3.可索引接口"></a>3.可索引接口</h3><blockquote>
<p>对数组、对象的约束（不常用）</p>
</blockquote>
<pre><code class="ts">//对 数组的约束
interface userArray {
    [index: number]: string;
}
let arr: userArray = [&#39;a&#39;, &#39;123&#39;];


// 对 对象的约束
interface userObj {
    [index: string]: string | number;
}
let obj: userObj = {
    name: &#39;张三&#39;,
}

// 对 数组对象的约束
interface userArrayObj {
    [index: number]: userObj
}
let list: userArrayObj = [{
    name: &#39;张三&#39;,
    age: 20
}];</code></pre>
<h3 id="4-类-类型接口"><a href="#4-类-类型接口" class="headerlink" title="4.类 类型接口"></a>4.类 类型接口</h3><blockquote>
<p>对类的约束 和抽象类有点相似</p>
</blockquote>
<pre><code class="ts">// 类 类型接口  implements 实现接口
interface IAnimal {
    name: string;
    age: number;
    eat(str: string): void;
    run(value: number): string;
}

class Dogs implements IAnimal {
    name: string;
    age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    eat(str: string): void {
        console.log(str);
    }
    run(value: number): string {
        return &#39;我跑了&#39; + value;
    }
}</code></pre>
<h3 id="5-接口扩展（接口可以继承接口）"><a href="#5-接口扩展（接口可以继承接口）" class="headerlink" title="5.接口扩展（接口可以继承接口）"></a>5.接口扩展（接口可以继承接口）</h3><pre><code class="ts">interface IAnimal {
    name: string;
    age: number;
    eat(str: string): void;
    run(value: number): string;
}

interface IPerson extends IAnimal {
    cate: string;
    print(str: string): void;
}

class Person implements IPerson {

    name: string;
    age: number;
    cate: string;
    constructor(name: string, age: number, cate: string) {
        this.name = name;
        this.age = age;
        this.cate = cate;
    }

    print(str: string): void {
        console.log(str);
    }
    eat(str: string): void {
        console.log(str + &#39;吃饭&#39;)
    }
    run(value: number): string {
        return &#39;我跑了&#39; + value;
    }
}

let s = new Person(&#39;小小&#39;, 20, &#39;人&#39;);
console.log(s.run(60));
s.eat(&#39;小小&#39;);</code></pre>
<pre><code class="ts">interface IAnimal {
    name: string;
    age: number;
    eat(str: string): void;
    run(value: number): string;
}

interface IPerson extends IAnimal {
    cate: string;
    print(str: string): void;
}

class Person implements IPerson {

    name: string;
    age: number;
    cate: string;
    constructor(name: string, age: number, cate: string) {
        this.name = name;
        this.age = age;
        this.cate = cate;
    }

    print(str: string): void {
        console.log(str);
    }
    eat(str: string): void {
        console.log(str + &#39;吃饭&#39;)
    }
    run(value: number): string {
        return &#39;我跑了&#39; + value;
    }
}


// 同时继承类 和 实现接口
class Programmer extends Person implements IPerson {
    constructor(name: string, age: number, cate: string) {
        super(name, age, cate);
    }

    print(str: string): void {
        console.log(str);
    }
    eat(str: string): void {
        console.log(str + &#39;吃饭&#39;)
    }
    run(value: number): string {
        return &#39;我跑了&#39; + value;
    }
}

let s = new Person(&#39;小小&#39;, 20, &#39;人&#39;);
console.log(s.run(60));
s.eat(&#39;小小&#39;);</code></pre>

            </div>
            <hr>
            <div>
              <p>
                
                  <span>
                <i class="iconfont icon-inbox"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a>
                      &nbsp;
                    
                  </span>&nbsp;&nbsp;
                
                
                  <span>
                <i class="iconfont icon-tag"></i>
                    
                      <a class="hover-with-bg" href="/tags/TS/">TS</a>
                    
                  </span>
                
              </p>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" target="_blank" rel="nofollow noopener noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script defer src="//unpkg.com/valine/dist/Valine.min.js"></script>

  <script type="text/javascript">
    var notify = 'false' === 'true';
    var verify = 'false' === 'true';
    var oldLoad = window.onload;
    window.onload = function () {
      new Valine({
        el: '#vcomments',
        notify: notify,
        verify: verify,
        app_id: "RVi2nheifsyLgdNUtOODWrEk-gzGzoHsz",
        app_key: "IcQeTY6Y778SNjPL5dwy9JOs",
        placeholder: "说点什么",
        avatar: "/retro",
        meta: ['nick', 'mail', 'link'],
        pageSize: "10",
      });
      oldLoad && oldLoad();
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc-start"></div>
<div id="toc">
  <p class="h5"><i class="far fa-list-alt"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a class="z-depth-1" id="scroll-top-button" href="#" role="button">
      <i class="fa fa-chevron-up scroll-top-arrow" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><b>Hexo</b></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"> <b>Fluid</b></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/popper.js/1.16.1/umd/popper.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="https://cdn.staticfile.org/mdbootstrap/4.13.0/js/mdb.min.js" ></script>
<script  src="/js/main.js" ></script>


  <script  src="/js/lazyload.js" ></script>



  
  <script  src="https://cdn.staticfile.org/tocbot/4.10.0/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var navHeight = $('#navbar').height();
      var post = $('#post');
      var toc = $('#toc');
      var tocLimMax = post.offset().top + post.height() - navHeight;

      $(window).scroll(function () {
        var tocLimMin = $('#toc-start').offset().top - navHeight;
        var scroH = document.body.scrollTop + document.documentElement.scrollTop;

        if (tocLimMin <= scroH && scroH <= tocLimMax) {
          toc.css({
            'display': 'block',
            'position': 'fixed',
            'top': navHeight,
          });
        } else if (scroH <= tocLimMin) {
          toc.css({
            'position': '',
            'top': '',
          });
        } else if (scroH > tocLimMax) {
          toc.css('display', 'none');
        }
      });
      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '.post-content',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        scrollSmooth: true,
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc > p').css('visibility', 'visible');
      }
      var offset = $('#board-ctn').css('margin-right')
      $('#toc-ctn').css({
        'right': offset
      })
    });
  </script>










<!-- Plugins -->



  <script  src="https://cdn.staticfile.org/prettify/188.0.0/prettify.min.js" ></script>
  <script>
    $(document).ready(function () {
      $('pre').addClass('prettyprint  linenums');
      prettyPrint();
    })
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "TS中的接口&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      getSearchFile(path);
      this.onclick = null
    }
  </script>



  <script defer src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <script>
    $("#post img:not(.no-zoom img, img[no-zoom])").each(
      function () {
        var element = document.createElement("a");
        $(element).attr("data-fancybox", "images");
        $(element).attr("href", $(this).attr("src"));
        $(this).wrap(element);
      }
    );
  </script>





  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  








</body>
</html>
